/* File: NISave.m - (Interactive) Unix shell version of NISavePanel
 *
 * By: Christopher Lane (lane@sumex-aim.stanford.edu)
 *
 * Date: 10 November 1992
 *
 * Copyright: 1991 & 1992 by The Leland Stanford Junior University.
 * This program may be distributed without restriction for non-commercial use.
 */

#import <stdlib.h>
#import <getopt.h>
#import <strings.h>
#import <sys/param.h>
#import <nikit/NISavePanel.h>
#import <appkit/Application.h>

#define USAGE "usage: %s [-d directory] [-t title] [-p prompt] [-f directory]\n"
#define EXIT_USAGE (2)
#define SEPARATOR "/"

const char *fullPath(const char *parent, const char *name)
{
	static char buffer[MAXPATHLEN];
	
	if(parent == NULL) return name;
	
	if(strcmp(strcpy(buffer, parent), SEPARATOR) != 0) (void) strcat(buffer, SEPARATOR);
	
	return strcat(buffer, name);
}

void main(int argc, char *argv[])
{
	const char *title = NULL, *prompt = NULL, *path = NULL, *string = "";
	int option, status = EXIT_SUCCESS;
	
	NXApp = [Application new];
	
	while ((option = getopt(argc, argv, "d:t:p:f:")) != EOF)
		switch (option) {
		case 'd': path = optarg; break;
		case 't': title = optarg; break;
		case 'p': prompt = optarg; break;
		case 'f': string = optarg; break;
		default : status = EXIT_USAGE;
		}
	if (optind < argc) status = EXIT_USAGE;	
	
	if (status == EXIT_USAGE) (void) fprintf(stderr, USAGE, [NXApp appName]);
	else {
		int flags, context = [NXApp activateSelf:YES];
		NISavePanel *panel = [NISavePanel new];
	
		if (prompt != NULL) [panel setListTitle:(char *) prompt];
		if (title != NULL) [panel setPanelTitle:(char *) title];
		if (path != NULL) [panel setStartingDomainPath:path];
	
		if ((flags = [panel runModalWithString:(char *) string]) == NX_OKTAG)
			(void) puts(fullPath([panel domain], [panel directory]));
		else status = flags;

		[panel free];
		
		if (context) (void) [NXApp activate:context];
		}
	
	[NXApp free];
	
	exit(status);
}
